import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Website } from './entities/website.entity';
import { PageView } from './entities/page-view.entity';

@Injectable()
export class IpService {
  constructor(
    @InjectRepository(Website)
    private websiteRepository: Repository<Website>,
    @InjectRepository(PageView)
    private pageViewRepository: Repository<PageView>,
  ) {}

  async getIpVisits(ip: string, websiteId?: number, startDate?: string, endDate?: string): Promise<any> {
    try {
      const queryBuilder = this.pageViewRepository.createQueryBuilder('pv')
        .where('pv.ip = :ip', { ip });
      if (websiteId) {
        queryBuilder.andWhere('pv.websiteId = :websiteId', { websiteId });
      }
      if (startDate && endDate) {
        queryBuilder.andWhere('pv.createdAt BETWEEN :startDate AND :endDate', {
          startDate: new Date(startDate),
          endDate: new Date(endDate)
        });
      } else if (startDate) {
        queryBuilder.andWhere('pv.createdAt >= :startDate', {
          startDate: new Date(startDate)
        });
      } else if (endDate) {
        queryBuilder.andWhere('pv.createdAt <= :endDate', {
          endDate: new Date(endDate)
        });
      }
      const visits = await queryBuilder
        .leftJoinAndSelect('pv.website', 'website')
        .orderBy('pv.createdAt', 'DESC')
        .getMany();
      const stats = {
        totalVisits: visits.length,
        uniqueUrls: new Set(visits.map(v => v.url)).size,
        websites: new Set(visits.map(v => v.websiteId)).size,
        firstVisit: visits.length > 0 ? visits[visits.length - 1].createdAt : null,
        lastVisit: visits.length > 0 ? visits[0].createdAt : null,
      };
      return {
        ip,
        stats,
        visits
      };
    } catch (error) {
      throw new Error(`获取IP访问详情失败: ${error.message}`);
    }
  }

  // 获取某网站所有访问过的IP及统计信息
  async getWebsiteIps(websiteId: number): Promise<any[]> {
    // 查询所有访问过的IP
    const qb = this.pageViewRepository.createQueryBuilder('pv')
      .select('pv.ip', 'ip')
      .addSelect('COUNT(*)', 'totalVisits')
      .addSelect('MAX(pv.createdAt)', 'lastVisit')
      .addSelect('MAX(pv.device)', 'device')
      .addSelect('MAX(pv.browser)', 'browser')
      .addSelect('MAX(pv.os)', 'os')
      .addSelect('MAX(pv.country)', 'country')
      .addSelect('MAX(pv.city)', 'city')
      .where('pv.websiteId = :websiteId', { websiteId })
      .andWhere('pv.ip IS NOT NULL')
      .groupBy('pv.ip')
      .orderBy('lastVisit', 'DESC');
    return await qb.getRawMany();
  }
} 